/*
存储
*/
define('appStore', ['vue', 'vuex', 'component/wxUtils', 'appRoutes'], function (Vue, Vuex, { getHomeRoute, setTagNavListInLocalstorage, getTagNavListFromLocalstorage}, appRoutes) {
  Vue.use(Vuex)

  var showThisMenuEle = (item, access) => {
    if (item.meta && item.meta.access && item.meta.access.length) {
      if (hasOneOf(item.meta.access, access)) return true
      else return false
    } else return true
  }
  var getMenus = (list, access) => {
    let res = []
    for (var itemIndex in list) {
      var item = list[itemIndex]
      // console.log(item)
      if (!item.meta || (item.meta && !item.meta.hideInMenu)) {
        let obj = {
          icon: (item.meta && item.meta.icon) || '',
          name: item.name,
          meta: item.meta
        }
        if (((item.children && item.children.length !== 0) || (item.meta && item.meta.showAlways)) && showThisMenuEle(item, access)) {
          obj.children = getMenus(item.children, access)
        }
        if (item.meta && item.meta.href) obj.href = item.meta.href
        if (showThisMenuEle(item, access)) res.push(obj)
      }
    }
    return res
  }
  var getBreadCrumbList = (routeMetched) => {
    let res = routeMetched.filter(item => {
      return item.meta === undefined || !item.meta.hide
    }).map(item => {
      let obj = {
        icon: (item.meta && item.meta.icon) || '',
        name: item.name,
        meta: item.meta
      }
      return obj
    })
    res = res.filter(item => {
      return !item.meta.hideInMenu
    })
    return [{
      name: 'home',
      to: '/home/index'
    }, ...res]
  }

  var store = new Vuex.Store({
    namespaced: false,
    state: {
      userName: '',
      userId: '',
      avatorImgPath: '',
      token: '',
      access: '',
      local: '',
      tagNavList: [],
      breadCrumbList: [],
      homeRoute: getHomeRoute(appRoutes)
    },
    getters: {
      menuList: (state, getters, rootState) => getMenus(appRoutes, rootState.access)
    },
    mutations: {
      setLocal(state, lang) {
        state.local = lang
      },
      setBreadCrumb(state, routeMetched) {
        state.breadCrumbList = getBreadCrumbList(routeMetched)
      },
      setTagNavList(state, list) {
        if (list) {
          state.tagNavList = [...list]
          setTagNavListInLocalstorage([...list])
        } else state.tagNavList = getTagNavListFromLocalstorage()
      },
      addTag(state, item, type = 'unshift') {
        if (state.tagNavList.findIndex(tag => tag.name === item.name) < 0) {
          if (type === 'push') state.tagNavList.push(item)
          else state.tagNavList.unshift(item)
          setTagNavListInLocalstorage([...state.tagNavList])
        }
      }
    }
  })
  return store
})
